package com.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.SystemConstants;
import com.common.domain.dto.AppointmentDto;
import com.common.domain.dto.DoctorDto;
import com.common.domain.entity.*;
import com.common.domain.vo.*;
import com.common.enums.AppHttpCodeEnum;
import com.common.mapper.*;
import com.common.service.DoctorService;
import com.common.service.LeaveService;
import com.common.service.UserService;
import com.common.util.BeanCopyUtils;
import com.common.util.DateUtil;
import com.common.util.RedisCache;
import com.common.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author pc
* @description 针对表【sys_doctor】的数据库操作Service实现
* @createDate 2023-09-02 11:17:55
*/
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
implements DoctorService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ConsultationMapper consultationMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public ResponseResult getDoctorInfo() {
        List<DoctorVo> list = doctorMapper.getDoctorInfo();
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult getDoctorDetail(Long id) {
        List<CommentVo> list = commentMapper.getDoctorCommentInfo(id);
        return ResponseResult.okResult(list);
    }

    @Override
    public List<Long> getDoctorLeaveInfo(Long id, String type)  {
        List<Map<String, String>> list = doctorMapper.getDoctorLeaveInfo(id, type);
        List<Long> dateTimeList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> stringDateMap = list.get(i);
            String startTime  = stringDateMap.get("startTime");
            String endTime  = stringDateMap.get("endTime");
            Date startTimeDate = null;
            Date endTimeDate = null;

             startTimeDate = DateUtil.StringToDate(startTime);
             endTimeDate = DateUtil.StringToDate(endTime);

            List<Date> dates = findDates(startTimeDate, endTimeDate);
            for (Date date:
                 dates) {
                dateTimeList.add(date.getTime());
            }
        }

        //排除预约
        List<String> userConsultationInfoDateList = consultationMapper.
                getUserConsultationInfoDateList(SecurityUtils.getUserId());

        for (String date:
                userConsultationInfoDateList) {
            dateTimeList.add(DateUtil.StringToDate(date).getTime());
        }


        return dateTimeList;
    }

    @Override
    public ResponseResult allDoctorList(Integer pageNum, Integer pageSize, String name, String departmentId) {
        PageHelper.startPage(pageNum,pageSize);

        List<DoctorInfoVo> list =  doctorMapper.allDoctorList(name,departmentId, null);

        PageInfo<DoctorInfoVo> pageInfo = new PageInfo<>(list);

        pageInfo.setList(list);

        return ResponseResult.okResult(pageInfo);
    }

    @Override
    public ResponseResult deleteDoctor(String ids) {
        String[] split = ids.split(",");
        userMapper.deleteBatchIds(Arrays.asList(split));

        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Doctor::getNumber,Arrays.asList(split));
        doctorMapper.delete(queryWrapper);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult insertDoctor(DoctorDto doctorDto) {
        User user = new User();
        String encodePassword = passwordEncoder.encode(doctorDto.getPassword());
        user.setUserName(doctorDto.getUserName());
        user.setPassword(encodePassword);
        user.setSex(doctorDto.getSex());
        user.setType(SystemConstants.DOCTOR);

        userMapper.insert(user);

        Doctor doctor = new Doctor();
        doctor.setNumber(user.getId());
        doctor.setEmail(doctorDto.getEmail());
        doctor.setDepartmentId(doctorDto.getDepartmentId());
        doctor.setIntroduction(doctorDto.getIntroduction());
        doctor.setName(doctorDto.getDoctorName());
        save(doctor);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(13L);
        userRoleMapper.insert(userRole);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateDoctor(DoctorDto doctorDto) {
        User user = new User();
        user.setSex(doctorDto.getSex());
        if(StringUtils.hasText(doctorDto.getPassword())) {
            String encodePassword = passwordEncoder.encode(doctorDto.getPassword());
            user.setPassword(encodePassword);
        }
        user.setId(doctorDto.getId());
        userMapper.updateById(user);

        Doctor doctor = new Doctor();
        doctor.setNumber(doctorDto.getId());
        doctor.setEmail(doctorDto.getEmail());
        doctor.setDepartmentId(doctorDto.getDepartmentId());
        doctor.setIntroduction(doctorDto.getIntroduction());
        doctor.setName(doctorDto.getDoctorName());

        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getNumber, user.getId());
        doctorMapper.update(doctor, queryWrapper);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult changeStatus(Long id, String status) {
        return null;
    }

    @Override
    public DoctorInfoVo getInfo() {
        List<DoctorInfoVo> list =  doctorMapper.allDoctorList(null,null, SecurityUtils.getUserId());
        return  list.get(0);
    }

    @Override
    public ResponseResult addLeaveInfo(Leave leave) {
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getNumber, SecurityUtils.getUserId());
        Doctor doctor = doctorMapper.selectOne(queryWrapper);
        leave.setDoctorId(doctor.getId());
        leaveMapper.insert(leave);
        return  ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateLeaveInfo(Leave leave) {
        leave.setStatus("0");
        leaveMapper.updateById(leave);
        return ResponseResult.okResult();
    }


    public static List<Date> findDates(Date startDate, Date endDate) {
        Calendar cStart = Calendar.getInstance();
        cStart.setTime(startDate);

        List dateList = new ArrayList();
        //加上起始日期
        dateList.add(startDate);
        // 此日期是否在指定日期之后
        while (endDate.after(cStart.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            cStart.add(Calendar.DAY_OF_MONTH, 1);
            // 如果终止日期小于当前日期
            if(endDate.compareTo(cStart.getTime()) < 0)
                break;
            dateList.add(cStart.getTime());
        }
        return dateList;
    }


}
